#include <REGX52.H>
#include "timer.c"

/**
 * 初始状态：LED熄灭。
 * 第一次按键按下：开始计时，LED常亮。
 * 第二次按键按下：停止计时，LED以闪烁次数表示秒数（如计时3秒：闪烁3次，不足1秒的不算在计时内）。
 */

void delay_ms(unsigned int ms)
{
    unsigned int i, j;
    for (i = 0; i < ms; i++)
    {
        for (j = 0; j < 123; j++)
            ;
    }
}

sbit BTN = P2 ^ 6;
sbit LED = P2 ^ 0;

volatile unsigned int led_light_count = 0;
unsigned int isr_count = 0;

#define ONE_SEC_COUNT 100

#define STATE_LED_ON 0
#define STATE_LED_FLICKER 1
#define STATE_LED_OFF 2

unsigned char state = STATE_LED_OFF;

/**
 * 当没有按键按下，返回0xFF
 * 按下返回0
 */
unsigned char btn_scan()
{
    if (BTN == 0)
    {
        delay_ms(20);
        if (BTN == 0)
        {
            while (BTN == 0)
                ;
            return 0;
        }
    }
    return 0xFF;
}

void time0_ISR() interrupt 1
{
    // 11.0592  10ms
    TH0 = 0xDB;
    TL0 = 0xFF;

    isr_count++;

    if (isr_count > ONE_SEC_COUNT)
    {
        isr_count = 0;
        if (state == STATE_LED_ON)
        {
            led_light_count++;
        }

        if (state == STATE_LED_FLICKER)
        {
            if (led_light_count > 0)
            {
                led_light_count--;
                LED = ~LED;
            }
            else
            {
                LED = 0;
                state = STATE_LED_OFF;
            }
        }
    }
}

void main()
{
    timer0_init();
    timer0_isr_on();
    LED = 0;

    while (1)
    {
        switch (state)
        {
        case STATE_LED_OFF:
            if (btn_scan() != 0xFF)
            {
                state = STATE_LED_ON;
                LED = 1;
            }
            break;
        case STATE_LED_ON:
            if (btn_scan() != 0xFF)
            {
                LED = 0;
                TR0 = 0;
                TH0 = 0xDB;
                TL0 = 0xFF;
                led_light_count *= 2;
                state = STATE_LED_FLICKER;
                TR0 = 1;
            }
            break;
        case STATE_LED_FLICKER:
            break;
        default:
            break;
        }
    }
}